import React from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from './qdx-qs-redux';

export class Provider extends React.Component{
  static childContextTypes = {
    store: PropTypes.object
  }
  constructor(props, context){
    super(props, context)
    this.store = props.store
  }
  getChildContext(){
    return {
      store: this.store
    }
  }
  render(){
    return this.props.children
  }
}
//connect 处理的事情，1.将store传入到子组件中，对mapState，mapDispatch进行处理，使其变成props对组件有效
export const connect = (mapStateToProps, mapDispatchToProps) => (Comp) => {
  return class WrapComponent extends React.Component{
    static contextTypes = {
      store: PropTypes.object
    }
    constructor(props,context){
      super(props, context)
      this.state = {
        props: {}
      }
    }
    componentDidMount() {
      const {store} = this.context
      store.subscribe(() => this.update())
      this.update()
    }
    update(){
      const { store } = this.context
      const stateProps = mapStateToProps(store.getState())
      const dispatchProps = bindActionCreators(mapDispatchToProps, store.dispatch)
      this.setState({
        props:{
          ...this.state.props,
          ...stateProps,
          ...dispatchProps
        }
      })
    }
    render(){
      return (
        <Comp {...this.state.props}></Comp>
      )
    }
  }
}